<?php
/**
 * mock_fmw_api
 * XHSController.php
 * @author: Heze
 * Date: 2023/4/25 18:53
 */

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class XHSController extends Controller
{
    protected $orderId = '';

    protected $refundId = '';

    protected $refundType = 5; // 1-退货退款; 2-换货; 3-仅退款(OLD); 4-仅退款; 5-未发货仅退款;

    protected $afterStatus = 1; // 1-待审核; 2-待用户寄回; 3-待收货; 4-完成;

    protected $afterSaleOrderId = '2025051509006';

    protected $orderStatus = 2; // 订单状态，1已下单待付款 2已支付处理中 3清关中 4待发货 5部分发货 6待收货 7已完成 8已关闭 9已取消 10换货申请中

    public function test()
    {
        return [];
    }

    public function index(Request $request)
    {
        $method = $request->get('method');
        $method = str_replace('.', '_', $method);
        if (!method_exists($this, $method)) {
            echo sprintf("[%s] mock function not exists", $method);
            exit;
        }

        $this->refundId = sprintf('R%s_%s', date("YmdHis"), Str::random(4));
        $this->orderId = sprintf('mock_%s_%s', date("YmdHis"), Str::random(4));

        return $this->$method($request);
    }

    // 获取 token
    public function oauth_getAccessToken(Request $request)
    {
        $expiresAt = strtotime("+2 day") * 1000;
        $accessToken = date('YmdHis') . Str::random(6);

        return [
            'error_code' => '',
            'success' => true,
            'data' => [
                "accessToken" => sprintf("xhs_token_%s", $accessToken),
                "accessTokenExpiresAt" => $expiresAt,
                "refreshToken" => sprintf("xhs_refresh_token_%s", $accessToken),
                "refreshTokenExpiresAt" => $expiresAt,
                "sellerId" => "xhs_20250728",
                "sellerName" => "开放平台测试店1专卖店"
            ],
        ];
    }

    // 刷新 token
    public function oauth_refreshToken(Request $request)
    {
        $expiresAt = strtotime("+2 day") * 1000;
        $accessToken = date('YmdHis') . Str::random(6);

        return [
            'error_code' => '',
            'success' => true,
            'data' => [
                "accessToken" => sprintf("xhs_token_%s", $accessToken),
                "accessTokenExpiresAt" => $expiresAt,
                "refreshToken" => sprintf("xhs_refresh_token_%s", $accessToken),
                "refreshTokenExpiresAt" => $expiresAt,
                "sellerId" => "xhs_20250728",
                "sellerName" => "开放平台测试店1专卖店"
            ],
        ];
    }

    // 订单列表
    public function order_getOrderList(Request $request)
    {
        $orderList = [
            "orderId" => $this->orderId,
            "orderType" => 1,
            "orderStatus" => $this->orderStatus,
            "orderAfterSalesStatus" => 1,
            "cancelStatus" => 1,
            "createdTime" => 1612518379000,
            "paidTime" => 1612518379000,
            "updateTime" => 1612518379000,
            "deliveryTime" => 1612518379000,
            "cancelTime" => 1612518379000,
            "finishTime" => 1612518379000,
            "promiseLastDeliveryTime" => 1612518379000,
            "planInfoId" => "null",
            "planInfoName" => "null",
            "receiverCountryId" => "null",
            "receiverCountryName" => "中国",
            "receiverProvinceId" => "null",
            "receiverProvinceName" => "江苏省",
            "receiverCityId" => "null",
            "receiverCityName" => "苏州市",
            "receiverDistrictId" => "null",
            "receiverDistrictName" => "相城区",
            "customerRemark" => "null",
            "sellerRemark" => "null",
            "sellerRemarkFlag" => 1,
            "originalOrderId" => "P123***4123",
            "logistics" => "red_express"
        ];

        return [
            'error_code' => '',
            'success' => true,
            'data' => [
                "total" => 1,
                "pageNo" => 1,
                "pageSize" => 100,
                "maxPageNo" => 100,
                "orderList" => [$orderList]
            ]
        ];
    }

    // 订单详情
    public function order_getOrderDetail(Request $request)
    {
        $orderId = $request->get('orderId');

        $skuDetailList2 = $skuDetailList = [
            "skuId" => "XHSSKUA00001",
            "erpCode" => "SKUA00001",
            "barcode" => "SKUA00001",
            "scSkuCode" => "XHSSKUA00001",
            "quantity" => 1,
            "registerName" => "测试商品A",
            "skuName" => "测试商品A 颜色:红色",
            "taxPerSku" => 0,
            "pricePerSku" => 5990,
            "rawPricePerSku" => 5990,
            "paidAmountPerSku" => 5224,
            "redDiscountPerSku" => 766,
            "depositAmountPerSku" => 0,
            "merchantDiscountPerSku" => 0,
        ];

        $skuDetailList2['skuId'] = 'XHSSKUA00002';
        $skuDetailList2['erpCode'] = 'SKUA00002';
        $skuDetailList2['quantity'] = 1;
        $skuDetailList2['taxPerSku'] = 0;
        $skuDetailList2['pricePerSku'] = 5990;
        $skuDetailList2['rawPricePerSku'] = 5990;
        $skuDetailList2['paidAmountPerSku'] = 5225;
        $skuDetailList2['redDiscountPerSku'] = 765;
        $skuDetailList2['depositAmountPerSku'] = 0;
        $skuDetailList2['merchantDiscountPerSku'] = 0;

        $skuList = [
            "skuId" => "MAINXHSSKUA00001",
            "skuName" => "测试商品A 颜色:红色",
            "erpcode" => "SKUA00001",
            "skuSpec" => "null",
            "skuImage" => "null",
            "skuQuantity" => 2,
            "skuDetailList" => [$skuDetailList, $skuDetailList2],
            "totalPaidAmount" => 10449,
            "totalMerchantDiscount" => 0,
            "totalRedDiscount" => 1531,
            "totalTaxAmount" => 0,
            "totalNetWeight" => 0,
            "skuTag" => 0,
            "isChannel" => false,
            "channel" => ""
        ];

        $simpleDeliveryOrderList = [
            "deliveryOrderIndex" => "",
            "status" => 1,
            "expressTrackingNo" => "ZTO202212020311",
            "expressCompanyCode" => "ZTO",
            "skuIdList" => [
                "string"
            ]
        ];

        return [
            'error_code' => '',
            'success' => true,
            'data' => [
                "orderId" => $orderId,
                "orderType" => 1,
                "orderStatus" => $this->orderStatus,
                "orderAfterSalesStatus" => 1,
                "cancelStatus" => 1,
                "createdTime" => 1612518379000,
                "paidTime" => 1612518379000,
                "updateTime" => 1612518379000,
                "deliveryTime" => 1612518379000,
                "cancelTime" => 1612518379000,
                "finishTime" => 1612518379000,
                "promiseLastDeliveryTime" => 1612518379000,
                "planInfoId" => "601a***fb49",
                "planInfoName" => "不包邮-默认模板",
                "receiverCountryId" => "null",
                "receiverCountryName" => "中国",
                "receiverProvinceId" => "null",
                "receiverProvinceName" => "江苏",
                "receiverCityId" => "null",
                "receiverCityName" => "苏州",
                "receiverDistrictId" => "null",
                "receiverDistrictName" => "相城区",
                "customerRemark" => "请尽快送达",
                "sellerRemark" => "请尽快送达",
                "sellerRemarkFlag" => 1,
                "presaleDeliveryStartTime" => 1612518379000,
                "presaleDeliveryEndTime" => 1612518379000,
                "skuList" => [$skuList],
                "originalOrderId" => "null",
                "totalNetWeightAmount" => 0,
                "totalMerchantDiscount" => 0,
                "totalRedDiscount" => 1531,
                'merchantActualReceiveAmount' => 11980,
                "totalPayAmount" => 10449,
                "totalShippingFree" => 0,
                "unpack" => true,
                "expressTrackingNo" => "1021***1412",
                "expressCompanyCode" => "shunfeng",
                "receiverName" => "null",
                "receiverPhone" => "null",
                "receiverAddress" => "null",
                "boundExtendInfo" => [
                    "payNo" => "null",
                    "payChannel" => "null",
                    "productValue" => "",
                    "payAmount" => "",
                    "taxAmount" => "",
                    "shippingFee" => "",
                    "discountAmount" => "",
                    "zoneCodes" => [
                        "string"
                    ]
                ],
                "transferExtendInfo" => [
                    "internationalExpressNo" => "null",
                    "orderDeclaredAmount" => "",
                    "paintMarker" => "null",
                    "collectionPlace" => "null",
                    "threeSegmentCode" => "null"
                ],
                "openAddressId" => "null",
                "simpleDeliveryOrderList" => [$simpleDeliveryOrderList],
                "logistics" => "red_express"
            ]
        ];
    }

    // 订单收件人信息
    public function order_getOrderReceiverInfo(Request $request)
    {
        $receiverQueries = $request->get('receiverQueries');
        $orderId = $receiverQueries[0]['orderId'];
        $receiverInfo = [
            "orderId" => $orderId,
            "matched" => true,
            "receiverProvinceName" => "北京市",
            "receiverCityName" => "北京市",
            "receiverDistrictName" => "昌平区",
            "receiverTownName" => "北七家街道",
            "receiverName" => "张*",
            "receiverPhone" => "136****0400",
            "receiverAddress" => "北**"
        ];

        return [
            'error_code' => '',
            'success' => true,
            'data' => [
                'receiverInfos' => [$receiverInfo]
            ]
        ];
    }


    public function afterSale_getAfterSaleInfo(Request $request)
    {
        $sku = [
            "skuName" => "GALERIES LAFAYETTE 【森林北专属】时尚通勤扭结女士背心 象牙白 S",
            "image" => "//qimg.xiaohongshu.com/arkgoods/1040g3no31g0lodlf7i004a71vcjk3c7t6m763ao?itemId=67f73de21899f10001bba1d4&imageView2/1/w/320/h/320/q/90.jpeg",
            "appliedCount" => 1,
            "boughtCount" => 1,
            "price" => 300,
            "skuId" => "XHSSKUA00001",
            "skuERPCode" => "XHSSKUA00001",
            "barcode" => "SKUA00001",
            "scskucode" => "XHSSKUA00001",
            "variants" => [],
            "appliedTotalAmountYuan" => 300,
        ];

        return [
            "error_msg" => null,
            "data" => [
                'afterSaleInfo' => [
                    "returnsId" => $request->get('returnsId', 'RE' . date('YmdHis')),
                    "returnType" => $this->refundType,
                    "reasonId" => "",
                    "reason" => "质量问题",
                    "status" => $this->afterStatus,
                    "subStatus" => 301,
                    "receiveAbnormalType" => 1,
                    "orderId" => $this->afterSaleOrderId,
                    "exchangeOrderId" => $this->afterSaleOrderId,
                    "applyTime" => 1745980057000,
                    "closeReasonZh" => "",
                    "skus" => [
                        $sku
                    ],
                    "openAddressId" => "bfc7bb10253ee95ac84ae13d8a4457b0",
                    "reasonNameZh" => "尺寸/款式没选对",
                    "refundStatus" => 0,
                    "supportCarriageInsurance" => false,
                    "userId" => "5c73f6790000000010016f78",
                    "returnAddress" => [
                        "town" => "南法信地区",
                        "province" => "北京",
                        "phone" => "18201688720",
                        "city" => "北京市",
                        "street" => "北京市顺义区南法信镇空港物流园顺畅大道15号，嘉麟物流。",
                        "name" => "老佛爷退货组",
                        "fullAddress" => "北京 北京市 顺义区 南法信地区 北京市顺义区南法信镇空港物流园顺畅大道15号，嘉麟物流。",
                        "county" => "顺义区"
                    ],
                    "expireTime" => 1746590218000,
                    "cargoStatus" => 0,
                    "returnsTag" => 4,
                    "refundAmountYuan" => 0,
                    "appliedSkusAmountYuan" => 300,
                    "expectedRefundAmountYuan" => 300,
                    "appliedShipFeeAmountYuan" => 0,
                    "desc" => "",
                    "updatedAt" => 1745985492000
                ],
                'logisticsInfo' => [
                    'afterSale' => [
                        "fillExpressNoTime" => 1745985418000,
                        "expressNo" => "JDX039039562669",
                        "expressCompanyCode" => "jd",
                        "expressSignTime" => 0,
                        "expressCompanyName" => "京东快递"
                    ],
                    'order' => [
                        "expressNo" => "SF3182474367130",
                        "expressCompanyCode" => "shunfeng",
                        "expressCompanyName" => "顺丰速运"
                    ],
                ],
            ],
            "success" => true,
            "error_code" => null
        ];
    }


    // 批量解密
    public function data_batchDecrypt(Request $request)
    {
        $baseInfos = $request->get('baseInfos', []);
        $dataInfoLists = [];
        foreach ($baseInfos as $key => $baseInfo) {
            $expireAt = 0;
            $virtualNumber = null;
            $virtualExtendNumber = null;
            $virtualPhoneNumber = null;
            $virtualNumberFlag = false;
            switch ($key) {
                case 0:
                    $decryptedData = '张恒';
                    break;
                case 1:
                    $decryptedData = '136' . rand(0000, 9999) . '0400';

                    $virtualNumberFlag = false;
                    $virtualPhoneNumber = $decryptedData;
                    $expireAt = 3600 * 24 * 30 * 1000;
                    $virtualExtendNumber = rand(1000, 9999);
                    $virtualNumber = sprintf('%s-%s', $decryptedData, $virtualExtendNumber);
                    break;
                case 2:
                    $decryptedData = '北七家';
                    break;
                default:
                    $decryptedData = $baseInfo['encryptedData'];
            }

            $dataInfoLists[] = [
                "dataTag" => $baseInfo['dataTag'],
                "encryptedData" => $baseInfo['encryptedData'],
                "decryptedData" => $decryptedData,
                "errorCode" => 0,
                "errorMsg" => null,
                "expireAt" => $expireAt, // 隐私号过期时间（毫秒时间戳）
                "virtualExtendNumber" => $virtualExtendNumber, // 隐私号 分机号（4位分机号格式）
                "virtualNumber" => $virtualNumber, // 隐私号（11位手机号-4位分机号格式）
                "virtualNumberFlag" => $virtualNumberFlag, // 隐私号标识（true为隐私号，false为真实手机号）
                "virtualPhoneNumber" => $virtualPhoneNumber // 隐私号-主机号（11位手机号格式）
            ];
        }

        return [
            'error_code' => '',
            'success' => true,
            'data' => [
                'dataInfoList' => $dataInfoLists
            ]
        ];
    }

    // 售后列表
    public function afterSale_listAfterSaleApi(Request $request)
    {
        $afterSaleList = [
            "returnsId" => $this->refundId,
            "returnType" => $this->refundType,
            "reasonId" => "",
            "reason" => "质量问题",
            "status" => $this->afterStatus,
            "subStatus" => 301,
            "receiveAbnormalType" => "",
            "orderId" => $this->afterSaleOrderId,
            "exchangeOrderId" => $this->afterSaleOrderId,
            "userId" => "4912831012",
            "createdTime" => 1619332984285,
            "returnExpressNo" => "6112***4748",
            "returnExpressCompany" => "中通",
            "returnAddress" => "上海市徐汇区*****",
            "shipNeeded" => 1,
            "refunded" => true,
            "refundStatus" => 108,
            "autoReceiveDeadline" => 1619332984285,
            "useFastRefund" => true,
            "updateTime" => 1619332984285,
            "returnExpressCompanyCode" => "",
            "expectedRefundAmount" => 100
        ];

        return [
            'error_code' => '',
            'success' => true,
            'data' => [
                "total" => 100,
                "pageNo" => 1,
                "pageSize" => 50,
                "haxNext" => true,
                "simpleAfterSaleList" => [$afterSaleList],
                "maxPageNo" => 10
            ]
        ];
    }

    // 售后详情
    public function afterSale_getAfterSaleDetail(Request $request)
    {
        $afterSaleId = $request->get('afterSaleId');

        $skus2 = $skus = [
            "skuId" => "64c079ba54109e0001f43f67",
            "skuName" => "测试商品",
            "barcode" => "SKUA00001",
            "scSkucode" => "SKUA00001",
            "image" => "http://img.xiaohongshu.com/items/3135edc58855dcf047fc39161ee9f687@2o.jpg",
            "price" => 50,
            "boughtCount" => 1,
            "appliedCount" => 1,
            "returnedCount" => 1,
            "refundedCount" => 1,
            "returnPrice" => 50,
            "exchangeSkuId" => "64c079bb54109e0001f43f73",
            "exchangeSkuName" => "测试换货商品",
            "exchangeSkuImage" => "http://img.xiaohongshu.com/items/3135edc58855dcf047fc39161ee9f687@2o.jpg",
            "exchangeScskuCode" => "SKUA00003",
            "exchangeBarcode" => "SKUA00003"
        ];

        $skus2['skuId'] = '64c079bb54109e0001f43f6d';
        $skus2['barcode'] = 'SKUA00002';
        $skus2['scSkucode'] = 'SKUA00002';

        return [
            'error_code' => '',
            'success' => true,
            'data' => [
                "returnsId" => $this->refundId,
                "returnType" => $this->refundType,
                "reasonId" => "",
                "reason" => "质量问题",
                "status" => $this->afterStatus,
                "subStatus" => 301,
                "receiveAbnormalType" => 1,
                "orderId" => $this->afterSaleOrderId,
                "exchangeOrderId" => $this->afterSaleOrderId,
                "userId" => "1419231",
                "createdAt" => 1617724800,
                "returnExpressNo" => "6411****2491",
                "returnExpressCompany" => "中通",
                "returnAddress" => "上海是徐汇区****",
                "shipNeeded" => "",
                "refunded" => true,
                "refundStatus" => 1,
                "autoReceiveDeadline" => 1617724800,
                "useFastRefund" => "",
                "proofPhotos" => [
                    "string"
                ],
                "desc" => "质量不好",
                "note" => "质量不好",
                "refundTime" => 1617724800,
                "fillExpressTime" => 1617724800,
                "expressSignTime" => 1617724800,
                "skus" => [$skus, $skus2],
                "refundFee" => 100,
                "returnExpressRefundable" => true,
                "returnExpressRefunded" => "",
                "expectRefundFee" => 110,
                "updatedAt" => 1617724800,
                "returnExpressCompanyCode" => "",
                "openAddressId" => "",
                "expectedRefundAmount" => 100
            ]
        ];
    }

    // 开票列表查询
    public function invoice_getInvoiceList(Request $request)
    {
        // 开票状态, 1-待开票; 2-暂停中; 3-冻结中; 4-开票中; 5-开票失败; 6-已开票; 7-已作废;
        $invoiceStatus = 1;
        // 系统开票号
        $xhsInvoiceNo = time();
        // 发票类型, 0-发票类型未知; 1-增值税专用发票; 2-增值税纸质普通发票; 3-增值税电子普通发票; 4-形式发票;
        $invoiceType = 3;

        $pageNum = $request->get('pageNum', 1);

        $invoiceRecord = [
            "invoiceStatus" => $invoiceStatus,
            "xhsInvoiceNo" => $xhsInvoiceNo,
            "applyTime" => "",
            "title" => "",
            "taxNo" => "",
            "taxBankAccount" => "",
            "taxBankName" => "",
            "invoiceType" => $invoiceType,
            "invoiceAmt" => "",
            "invoiceNos" => "",
            "invoiceTotalAmt" => "",
            "refNo" => $request->get('refNo', ''),
            "titleType" => "",
            "updatedTime" => "",
            "attrMap" => "",
            "itemList" => [],
            "invoiceFileList" => [],
            "picUrl" => "",
            "pdfUrl" => ""
        ];

        return [
            'error_code' => '',
            'success' => true,
            'data' => [
                "total" => 1,
                "totalPage" => 1,
                "pageIndex" => 1,
                "pageSize" => 50,
                "invoiceRecords" => $pageNum > 1 ? [] : [
                    $invoiceRecord
                ],
            ]
        ];
    }

    // 开票结果回传（正向蓝票开具）
    public function invoice_confirmInvoice(Request $request)
    {
        return [
            'error_code' => '',
            'success' => true,
            'data' => [
                'result' => $request->toArray()
            ]
        ];
    }

    // 订单发货
    public function order_orderDeliver(Request $request)
    {
        return [
            'error_code' => '',
            'success' => true,
            'data' => []
        ];
    }

    // 查询电子面单模板列表
    public function express_queryEbillTemplates(Request $request)
    {
        $cpCode = $request->get('cpCode', '');

        $templateList = [
            [
                'id' => 3,
                'cpCode' => 'yunda',
                'brandCode' => '',
                'templateType' => '100*180',
                'templateCustomerType' => 0,
                'templateName' => '韵达快递标准模板',
                'templateDesc' => '',
                'templatePreviewUrl' => 'http://cloudprint.cainiao.com/template/standard/403585/7'
            ],
            [
                'id' => 5,
                'cpCode' => 'shunfeng',
                'brandCode' => '',
                'templateType' => '100*152',
                'templateCustomerType' => 0,
                'templateName' => '顺丰速运标准模板',
                'templateDesc' => '',
                'templatePreviewUrl' => 'http://cloudprint.cainiao.com/template/standard/1501/72'
            ],
        ];

        $list = [];
        if ($cpCode) {
            foreach ($templateList as $temp) {
                if ($temp['cpCode'] == $cpCode) {
                    $list[] = $temp;
                }
            }
        } else {
            $list = $templateList;
        }
        return [
            'error_code' => 0,
            'error_msg' => '',
            'success' => true,
            'data' => [
                'templateList' => $list
            ]
        ];
    }

    // 批量取号
    public function express_createEbillOrders(Request $request)
    {
        $cpCode = $request->get('cpCode');
        $tradeOrderInfoList = $request->get('tradeOrderInfoList');
        if (empty($tradeOrderInfoList) || !$cpCode) {
            return [
                'error_code' => 0,
                'error_msg' => '',
                'success' => true,
                'data' => [
                    'wayBillList' => []
                ]
            ];
        }

        $printData = [
            "encryptedData" => "encrypttext-test",
            "signature" => "MD:lH0r2gNxcIuY7dY3VvV4ag==",
            "templateURL" => "http://cloudprint.cainiao.com/template/standard/644703",
            "ver" => "waybill_print_xiaohongshu_secret"
        ];


        $waybillList = [];
        foreach ($tradeOrderInfoList as $dto) {
            $waybillCode = sprintf('XCXD_XHS__%s', date('YmdHis', time()));
            $waybillList[] = [
                'objectId' => $dto['objectId'],
                'waybillCode' => $waybillCode,
                'printData' => json_encode($printData),
                'parentWaybillCode' => '',
                'extraInfo' => '',
                'cpCode' => $cpCode,
                'customerPrintData' => "{\\\"data\\\":{\\\"item\\\":[\\\"商品名称\\\"],\\\"order\\\":[\\\"P000000001\\\"]},\\\"templateURL\\\":\\\"https://cloudprint.cainiao.com/template/standard/629505/24\\\"}"
            ];
        }

        return [
            'error_code' => 0,
            'error_msg' => '',
            'success' => true,
            'data' => [
                'wayBillList' => $waybillList,
                'subErrorCode' => ''
            ]
        ];
    }

    // 更新面单
    public function express_updateEbillOrder(Request $request)
    {
        $cpCode = $request->get('cpCode');
        $waybillCode = $request->get('waybillCode');
        $objectId = $request->get('objectId');
        $packageInfo = $request->get('packageInfo');

        return [
            'error_code' => 0,
            'error_msg' => '',
            'success' => true,
            'data' => [
                'waybill' => [
                    'objectId' => $objectId,
                    'waybillCode' => $waybillCode,
                    'printData' => "{\\\"encryptedData\\\":\\\"encrypttext-test2\\\",\\\"signature\\\":\\\"MD:lH0r2gNxcIuY7dY3VvV4ag==\\\",\\\"templateURL\\\":\\\"http://cloudprint.cainiao.com/template/standard/644703\\\",\\\"ver\\\":\\\"waybill_print_xiaohongshu_secret\\\"}",
                    'parentWaybillCode' => '',
                    'extraInfo' => '',
                    'cpCode' => $cpCode,
                    'customerPrintData' => "{\\\"data\\\":{\\\"item\\\":[\\\"商品名称\\\"],\\\"order\\\":[\\\"P000000001\\\"]},\\\"templateURL\\\":\\\"https://cloudprint.cainiao.com/template/standard/629505/24\\\"}"
                ],
                'subErrorCode' => ''
            ]
        ];
    }

    // 取消面单
    public function express_cancelEbillOrder(Request $request)
    {
        return [
            'error_code' => 0,
            'error_msg' => '',
            'success' => true,
            'data' => [
                'subErrorCode' => ''
            ]
        ];
    }

    // 查询面单
    public function express_queryEbillOrder(Request $request)
    {
        $cpCode = $request->get('cpCode');
        $waybillCode = $request->get('waybillCode');
        return [
            'error_code' => 0,
            'error_msg' => '',
            'success' => true,
            'data' => [
                'waybillCode' => $waybillCode,
                'printData' => "{\\\"encryptedData\\\":\\\"encrypttext-test\\\",\\\"signature\\\":\\\"MD:lH0r2gNxcIuY7dY3VvV4ag==\\\",\\\"templateURL\\\":\\\"http://cloudprint.cainiao.com/template/standard/644703\\\",\\\"ver\\\":\\\"waybill_print_xiaohongshu_secret\\\"}",
                'parentWaybillCode' => '',
                'extraInfo' => '',
                'cpCode' => $cpCode,
                'customerPrintData' => "{\\\"data\\\":{\\\"item\\\":[\\\"商品名称\\\"],\\\"order\\\":[\\\"P000000001\\\"]},\\\"templateURL\\\":\\\"https://cloudprint.cainiao.com/template/standard/629505/24\\\"}"
            ]
        ];
    }

    public function common_getAddressRecord(Request $request)
    {
        $pageIndex = $request->get('pageIndex', 1);

        $addressDetail = [
            "sellerAddressRecordId" => 105380,
            "contactName" => "张xx",
            "phoneAreaCode" => "86",
            "phone" => "12312345678",
            "landlineAreaCode" => "",
            "landlinePhone" => "",
            "landlineExtensionNumber" => "",
            "countryCode" => "001",
            "provinceCode" => "220000",
            "cityCode" => "220100",
            "countyCode" => "",
            "townCode" => "",
            "countryName" => "中国大陆",
            "provinceName" => "吉林省",
            "cityName" => "长春市",
            "countyName" => "",
            "townName" => "",
            "address" => "111",
            "fullAddress" => "吉林省 长春市 111",
            "deliveryDefault" => "NON_DEFAULT",
            "aftersaleDefault" => "NON_DEFAULT",
            "version" => 1,
            "active" => "ACTIVE",
            "createTime" => 1663048640000,
            "updateTime" => 1663048640000
        ];

        $sellerAddressRecordList = $pageIndex == 1 ? [$addressDetail] : [];

        return [
            'error_code' => 0,
            'error_msg' => '',
            'success' => true,
            'data' => [
                "sellerAddressRecordList" => $sellerAddressRecordList,
                "total" => count($sellerAddressRecordList)
            ]
        ];
    }

    public function afterSale_rejectReasons(Request $request)
    {
        // 拒绝原因类型 1：审核拒绝 2：收货拒绝
        $rejectReasonType = $request->get('rejectReasonType', 1);

        $audioReasons = [
            [
                "reasonType" => $rejectReasonType,
                "reasonId" => 1,
                "reasonName" => "买家未能提供有效凭证"
            ],
            [
                "reasonType" => $rejectReasonType,
                "reasonId" => 2,
                "reasonName" => "API返回拒绝原因001"
            ],
            [
                "reasonType" => $rejectReasonType,
                "reasonId" => 99,
                "reasonName" => "其他"
            ],
        ];

        $confirmReasons = [
            [
                "reasonType" => $rejectReasonType,
                "reasonId" => 5,
                "reasonName" => "未收到退件，快递还在途中"
            ],
            [
                "reasonType" => $rejectReasonType,
                "reasonId" => 6,
                "reasonName" => "已与买家协商一致"
            ],
            [
                "reasonType" => $rejectReasonType,
                "reasonId" => 8,
                "reasonName" => "API返回拒绝原因001"
            ],
            [
                "reasonType" => $rejectReasonType,
                "reasonId" => 7,
                "reasonName" => "其他"
            ],
        ];

        return [
            'error_code' => 0,
            'error_msg' => '',
            'success' => true,
            'data' => [
                'rejectReasons' => $rejectReasonType == 1 ? $audioReasons : $confirmReasons,
            ]
        ];
    }

    public function afterSale_auditReturns(Request $request)
    {
        return [
            'error_code' => 0,
            'error_msg' => '',
            'success' => true,
            'data' => $request->toArray()
        ];
    }

    public function afterSale_confirmReceive(Request $request)
    {
        return [
            'error_code' => 0,
            'error_msg' => '',
            'success' => true,
            'data' => $request->toArray()
        ];
    }

    // 订单货款结算明细
    public function finance_pageQueryTransaction(Request $request)
    {
//        return [
//            'error_code' => null,
//            'error_msg' => null,
//            'success' => false,
//            'data' => [
//                "total" => 0,
//                "totalPage" => 0,
//                "pageNum" => 0,
//                "pageSize" => 0
//            ]
//        ];
        $transaction1 = [
            "transactionId" => 63068010701,
            "packageId" => '63062022082180107',
            "statementType" => 0,
            "transactionBizType" => 0,
            "settleBizType" => 0,
            "deliveryId" => '',
            "transactionBizNo" => 'S63068010701',
            "returnId" => '',
            "orderTime" => 1661043610000,
            "canSettleTime" => 1661043610000,
            "settledTime" => 1708593330000,
            "predictableSettleTime" => 1708593330000,
            "erqingType" => 1,
            "transactionSettleStatus" => 4,
            "commonSettleStatus" => 1,
            "amount" => '164.5',
            "goodsAmount" => '200',
            "payAmount" => '200',
            "appPromotion" => '0',
            "freightAmount" => '0',
            "noFreightReason" => '无',
            "taxAmount" => '-55.5',
            "noTaxReason" => '',
            "freightTaxAmount" => '0',
            "noFreightTaxReason" => '',
            "commissionAmount" => '-30',
            "payChannelAmount" => '-5.5',
            "noPayChannelReason" => '',
            "cpsAmount" => '0',
            "installmentAmount" => '0',
            "noInstallmentReason" => '',
            "extraAmount" => '0',
            "noExtraReason" => '',
            "calculateRemark" => 'test_sale'
        ];
        $transaction2 = [
            "transactionId" => 63068010702,
            "packageId" => '63062022082180107',
            "statementType" => 2,
            "transactionBizType" => 1,
            "settleBizType" => 1,
            "deliveryId" => 'D63068010702',
            "transactionBizNo" => 'R63068010702',
            "returnId" => '630622088010701',
            "orderTime" => 1661043610000,
            "canSettleTime" => 1661043610000,
            "settledTime" => 1708593330000,
            "predictableSettleTime" => 1708593330000,
            "erqingType" => 0,
            "transactionSettleStatus" => 4,
            "commonSettleStatus" => 1,
            "amount" => '-124',
            "goodsAmount" => '-150',
            "payAmount" => '-150',
            "appPromotion" => '0',
            "freightAmount" => '0',
            "noFreightReason" => '无',
            "taxAmount" => '35.5',
            "noTaxReason" => '',
            "freightTaxAmount" => '0',
            "noFreightTaxReason" => '',
            "commissionAmount" => '22',
            "payChannelAmount" => '4',
            "noPayChannelReason" => '',
            "cpsAmount" => '0',
            "installmentAmount" => '0',
            "noInstallmentReason" => '',
            "extraAmount" => '0',
            "noExtraReason" => '',
            "calculateRemark" => 'test_refund'
        ];

        if ($request->get('pageNum') == 1) {
            $transactions = [$transaction1];
        } elseif ($request->get('pageNum') == 2) {
            $transactions = [$transaction2];
        } else {
            $transactions = [];
        }

        return [
            'error_code' => 0,
            'error_msg' => '',
            'success' => true,
            'data' => [
                "total" => 2,
                "totalPage" => 2,
                "pageNum" => $request->get('pageNum'),
                "pageSize" => $request->get('pageSize'),
                "transactions" => $transactions
            ]
        ];
    }

    // 其他服务款结算明细
    public function finance_pageQueryExpense(Request $request)
    {
        $expense1 = [
            "expenseId" => 63068010703,
            "packageId" => '63062022082180107',
            "baseBizType" => 7,
            "settleBizType" => 0,
            "bizNo" => 'IN63068010703',
            "settledTime" => 1708593530000,
            "erqingType" => 0,
            "transactionSettleStatus" => 4,
            "commonSettleStatus" => 1,
            "amount" => '1'
        ];

        if ($request->get('pageNum') == 1) {
            $expenses = [$expense1];
        } else {
            $expenses = [];
        }

        return [
            'error_code' => 0,
            'error_msg' => '',
            'success' => true,
            'data' => [
                "total" => 1,
                "totalPage" => 1,
                "pageNum" => $request->get('pageNum'),
                "pageSize" => $request->get('pageSize'),
                "expenses" => $expenses
            ]
        ];
    }

    public function product_getDetailSkuList(Request $request)
    {
        $erpCode = 'SKU_20240111003';

        $xhsItem11 = [
            'item' => [],
            'sku' => [
                "id" => sprintf("6123%s%s", date('YmdHis'), rand(1000, 9999)),
                "erpCode" => $erpCode,
                "scSkucode" => $erpCode,
                "name" => "默认",
                "itemId" => "64ff12f***fd12f1",
                "ipq" => 100,
                "originalPrice" => 88,
                "price" => 80,
                "stock" => 5000,
                "logisticsPlanId" => "5e37***a9f0",
                "whcode" => "C01",
                "priceType" => 1,
                "variants" => [],
                "deliveryTime" => [],
                "specImage" => "http://img.xiaohongshu.com/items/123456789",
                "barcode" => "RedTest20200507001",
                "rowNumber" => "",
                "logisticsName" => "red_auto",
                "buyable" => true,
                "unionItemDetails" => [],
                "createTime" => "",
                "updateTime" => "",
                "isChannel" => true,
                "isGift" => true
            ],
        ];
        $xhsItem22 = [
            'item' => [],
            'sku' => [
                "id" => sprintf("6123%s%s", date('YmdHis'), rand(1000, 9999)),
                "erpCode" => $erpCode,
                "scSkucode" => $erpCode,
                "name" => "默认",
                "itemId" => "64ff12f***fd12f1",
                "ipq" => 100,
                "originalPrice" => 88,
                "price" => 80,
                "stock" => 5000,
                "logisticsPlanId" => "5e37***a9f0",
                "whcode" => "C01",
                "priceType" => 1,
                "variants" => [],
                "deliveryTime" => [],
                "specImage" => "http://img.xiaohongshu.com/items/123456789",
                "barcode" => "RedTest20200507001",
                "rowNumber" => "",
                "logisticsName" => "red_auto",
                "buyable" => true,
                "unionItemDetails" => [],
                "createTime" => "",
                "updateTime" => "",
                "isChannel" => true,
                "isGift" => true
            ],
        ];

        $pageNo = $request->get('pageNo');
        $data = $pageNo == 1 ? [$xhsItem11, $xhsItem22] : [];

        return [
            'error_code' => 0,
            'error_msg' => '',
            'success' => true,
            'data' => [
                'total' => 2,
                'pageSize' => 1,
                'pageNO' => 1,
                'data' => $data
            ]
        ];
    }

    public function inventory_getSkuStock(Request $request)
    {
        return [
            'error_code' => 0,
            'error_msg' => '',
            'success' => true,
            'data' => [
                "skuId" => $request->get('skuId'),
                "apiVersion" => "V1",
                "skuStock" => [
                    "available" => 25,
                    "standalone" => "0",
                    "reserved" => "0",
                    "total" => 100,
                    "occupiedQuantity" => 35,
                    "productChannelQuantity" => 15,
                    "productChannelOccupiedQuantity" => 15,
                    "activityChannelQuantity" => 10,
                    "activityChannelOccupiedQuantity" => "0"
                ],
                "skuStockInfoWithWhcode" => [],
                "response" => [
                    "success" => "true",
                    "message" => "",
                    "code" => "0"
                ]
            ]
        ];
    }

    public function inventory_syncSkuStock(Request $request)
    {
        return response([
            'error_code' => -5000500,
            'error_msg' => '规格不存在',
            'success' => false,
        ], 400);


        return [
            'error_code' => 0,
            'error_msg' => '',
            'success' => true,
            'data' => [
                "skuId" => $request->get('skuId'),
                "skuStock" => [
                    "available" => $request->get('qty'),
                    "standalone" => $request->get('qty'),
                    "reserved" => $request->get('qty'),
                    "total" => $request->get('qty')
                ]
            ]
        ];
    }
}
